package cn.czg.cms.mapper;

import cn.czg.cms.entity.Message;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

@Mapper
public interface MessageMapper extends BaseMapper<Message> {

    /**
     * 查询两个用户的聊天记录，按发送时间升序排序，分页
     *
     * @param userId 当前用户ID
     * @param peerId 对方用户ID
     * @param offset 偏移量
     * @param limit  查询条数
     * @return List<Message>
     */
    @Select("SELECT * FROM message " +
            "WHERE ((sender_id = #{userId} AND receiver_id = #{peerId} AND deleted_by_sender = 0) " +
            "OR (sender_id = #{peerId} AND receiver_id = #{userId} AND deleted_by_receiver = 0)) " +
            "ORDER BY send_time ASC " +
            "LIMIT #{limit} OFFSET #{offset}")
    List<Message> selectChatHistory(@Param("userId") Long userId,
                                    @Param("peerId") Long peerId,
                                    @Param("offset") int offset,
                                    @Param("limit") int limit);

    @Select("""
            SELECT m1.*
            FROM message m1
            INNER JOIN (
                SELECT conversation_id, MAX(send_time) AS max_time
                FROM message
                WHERE sender_id = #{userId} OR receiver_id = #{userId}
                GROUP BY conversation_id
            ) m2 ON m1.conversation_id = m2.conversation_id AND m1.send_time = m2.max_time
            ORDER BY m1.send_time DESC
            """)
    List<Message> selectLastMessages(@Param("userId") Long userId);

    @Select("""
            SELECT COUNT(*)
            FROM message
            WHERE sender_id = #{otherUserId}
              AND receiver_id = #{myId}
              AND is_read = false
            """)
    Integer countUnread(@Param("myId") Long myId, @Param("otherUserId") Long otherUserId);
}

